package 剑指offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class 剑指Offer32II从上到下打印二叉树II {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList();
        if(root == null){
            return lists;
        }
        Deque<TreeNode> queue = new ArrayDeque();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();//当前size为本层节点的个数
            List list = new ArrayList<Integer>();
            for(int i = 0;i < size;i++){//循环size次刚好将本层的节点全部出队列
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }
}
